﻿using System.Security.Policy;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using SHZY.BaseData.Entitys.Common.Dto.Factory;
using SHZY.BaseData.Entitys.Common.Dto.Material;
using SHZY.BaseData.Entitys.Common.Dto.UsersiteRel;
using SHZY.BaseData.Entitys.Common.Entity;
using SHZY.BaseData.Entitys.WMS.Entity;
using SHZY.BaseData.Interfaces.Common;
using SHZY.Common.Core.Manager;
using SHZY.Common.Core.Security;
using SHZY.Common.Enum;
using SHZY.Common.Filter;
using SHZY.Common.Security;
using SHZY.DependencyInjection;
using SHZY.DynamicApiController;
using SHZY.FriendlyException;
using SHZY.Systems.Entitys.Permission;
using SHZY.Systems.Entitys.System;
using SHZY.Systems.Interfaces.System;
using SqlSugar;

namespace SHZY.BaseData.Common;

/// <summary>
/// 业务实现：人员与工厂绑定关系.
/// </summary>
[ApiDescriptionSettings(Tag = "BaseData", Name = "UsersiteRel", Order = 200)]
[Route("api/Common/BaseData/[controller]")]
public class ComBaseUsersiteRelService : IComBaseUsersiteRelService, IDynamicApiController, ITransient
{
    /// <summary>
    /// 服务基础仓储.
    /// </summary>
    private readonly ISqlSugarRepository<ComBaseUsersiteRelEntity> _repository;

    /// <summary>
    /// 服务基础仓储.-班组
    /// </summary>
    private readonly ISqlSugarRepository<ComBaseUsersiteRelEntity> _repository_children;

    /// <summary>
    /// 数据接口服务.
    /// </summary>
    private readonly IDataInterfaceService _dataInterfaceService;

    /// <summary>
    /// 用户管理.
    /// </summary>
    private readonly IUserManager _userManager;

    /// <summary>
    /// 初始化一个<see cref="ComBaseUsersiteRelService"/>类型的新实例.
    /// </summary>
    public ComBaseUsersiteRelService(
        ISqlSugarRepository<ComBaseUsersiteRelEntity> qmsBaseUsersiteRelRepository,
        IDataInterfaceService dataInterfaceService,
        ISqlSugarClient context,
        IUserManager userManager)
    {
        _repository = qmsBaseUsersiteRelRepository;
        _repository_children = qmsBaseUsersiteRelRepository;
        _dataInterfaceService = dataInterfaceService;
        _userManager = userManager;
    }

    /// <summary>
    /// 获取人员与工厂绑定关系.
    /// </summary>
    /// <param name="id">主键值.</param>
    /// <returns></returns>
    [HttpGet("{id}")]
    public async Task<dynamic> GetInfo(string id)
    {
        return (await _repository.FirstOrDefaultAsync(x => x.Id == id)).Adapt<ComBaseUsersiteRelInfoOutput>();
    }

    /// <summary>
    /// 获取人员与工厂绑定关系列表.
    /// </summary>
    /// <param name="input">请求参数.</param>
    /// <returns></returns>
    [HttpGet("")]
    public async Task<dynamic> GetList([FromQuery] ComBaseUsersiteRelListQueryInput input)
    {
        var queryable = _repository.Context.Queryable<ComBaseUsersiteRelEntity, ComBaseFactorystructureEntity, UserEntity>((a, b, c) => new JoinQueryInfos(JoinType.Left, a.Site == b.EnCode && b.Type == "Factory" &&  b.DeleteMark == null, JoinType.Left, a.UserId == c.Id && c.DeleteMark == null))
            .WhereIF(!string.IsNullOrEmpty(input.realName), (a, b, c) => c.RealName.Contains(input.realName))
            .WhereIF(!string.IsNullOrEmpty(input.site), (a, b, c) => a.Site.Contains(input.site))
            .Where((a, b, c) => a.DeleteMark == null)
            .WhereIF(!string.IsNullOrEmpty(input.keyword), (a, b, c) => a.UserId.Contains(input.keyword) || a.Site.Contains(input.keyword));
        if (!string.IsNullOrEmpty(input.sidx))
        {
            queryable.OrderBy(input.sidx + " " + input.sort);
        }
        else
        {
            queryable.OrderBy("RealName" + " " + "desc");
        }

        var data = await queryable.Select((a, b, c) => new ComBaseUsersiteRelListOutput
        {
            id = a.Id,
            userId = a.UserId,
            site = a.Site,
            fullName = b.FullName,
            realName = c.RealName,
            enabledMark = SqlFunc.IF(a.EnabledMark == 1).Return("正常").End("停用")
        }).ToPagedListAsync(input.currentPage, input.pageSize);
        return PageResult<ComBaseUsersiteRelListOutput>.SqlSugarPageResult(data);
    }

    /// <summary>
    /// 新建人员与工厂绑定关系.
    /// </summary>
    /// <param name="input">参数.</param>
    /// <returns></returns>
    [HttpPost("")]
    public async Task Create([FromBody] ComBaseUsersiteRelCrInput input)
    {
        for (int i = 0; i < input.userIds.Count; i++)
        {
            if (!await _repository.AnyAsync(x => x.UserId == input.userIds[i] && x.Site == input.site && x.DeleteMark == null))
            {
                var entity = input.Adapt<ComBaseUsersiteRelEntity>();
                entity.Id = SnowflakeIdHelper.NextId();
                entity.UserId = input.userIds[i];
                var isOk = await _repository.Context.Insertable(entity).IgnoreColumns(ignoreNullColumn: true).CallEntityMethod(m => m.Creator()).ExecuteCommandAsync();
                if (!(isOk > 0))
                {
                    throw Oops.Oh(ErrorCode.COM1000);
                }
            }
        }
    }

    /// <summary>
    /// 更新人员与工厂绑定关系.
    /// </summary>
    /// <param name="id">主键值.</param>
    /// <param name="input">参数.</param>
    /// <returns></returns>
    [HttpPut("{id}")]
    public async Task Update(string id, [FromBody] ComBaseUsersiteRelUpInput input)
    {
        if (await _repository.AnyAsync(x => x.UserId == input.userId && x.Site == input.site && x.Id != input.id && x.DeleteMark == null))
        {
            throw Oops.Oh("当前人员与工厂已绑定");
        }

        var entity = input.Adapt<ComBaseUsersiteRelEntity>();
        var isOk = await _repository.Context.Updateable(entity).UpdateColumns(it => new
        {
            it.UserId,
            it.Site,
            it.EnabledMark,
            it.LastModifyTime,
            it.LastModifyUserId
        }).CallEntityMethod(m => m.LastModify()).ExecuteCommandAsync();
        if (!(isOk > 0)) throw Oops.Oh(ErrorCode.COM1001);
    }

    /// <summary>
    /// 删除人员与工厂绑定关系.
    /// </summary>
    /// <returns></returns>
    [HttpDelete("{id}")]
    public async Task Delete(string id)
    {
        var entity = await _repository.SingleAsync(x => x.Id == id);
        var isOk = await _repository.Context.Updateable(entity).CallEntityMethod(m => m.Delete()).UpdateColumns(it => new { it.DeleteMark, it.DeleteTime, it.DeleteUserId }).ExecuteCommandHasChangeAsync();
        if (!isOk)
        {
            throw Oops.Oh(ErrorCode.COM1002);
        }
    }
}